package com.mainbo.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mainbo.core.common.constant.ConfigUtils;
import com.mainbo.core.common.constant.Const;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.shiro.ShiroUser;
import com.mainbo.core.util.AccountGenerator;
import com.mainbo.core.util.EncryptPassword;
import com.mainbo.modular.system.dao.PtAccountMapper;
import com.mainbo.modular.system.dao.PtRoleMapper;
import com.mainbo.modular.system.dao.PtTeacherMapper;
import com.mainbo.modular.system.dao.PtUserRoleMapper;
import com.mainbo.modular.system.model.*;
import com.mainbo.modular.system.model.meta.MetaKeys;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.model.vo.ExportInfoVo;
import com.mainbo.modular.system.service.IPtOrgService;
import com.mainbo.modular.system.service.IPtResourcesService;
import com.mainbo.modular.system.service.TeacherService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author xww
 * @Description //TODO
 * @Date 2020/2/26   14:17
 **/@Service
public class TeacherServiceImpl extends ServiceImpl<PtTeacherMapper, Teacher> implements TeacherService {
     @Resource
     private PtTeacherMapper teacherMapper;
     @Resource
     private IPtOrgService orgService;
    @Resource
    private AccountGenerator accountGenerator;
    @Resource
    private PtAccountMapper accountMapper;
    @Resource
    private IPtResourcesService resourcesService;
    @Resource
    private PtUserRoleMapper userRoleMapper;
    @Resource
    private PtRoleMapper ptRoleMapper;
    @Override
    public CommUser getOne(String name, String orgId) {
        return teacherMapper.getOne(name,orgId);
    }

    @Override
    public List<Teacher> findTeacherList(Teacher teacher, UserSearchModel um) {
        List<String> orgIds = new ArrayList<String>();
        if (StringUtils.isNotEmpty(um.getOrgId()) &&!"0".equals(um.getOrgId())) {
            teacher.setOrgId(um.getOrgId());
        } else if (um.getAreaId() != null && um.getAreaId() != 0) {
            List<PtOrg> orglist = new ArrayList<PtOrg>();

            if (um.getAreaId() != null) {
                orglist = orgService.getOrgByAreaId(um.getAreaId(), PtOrg.TP_SCHOOL);
            }
            for (PtOrg organization : orglist) {
                orgIds.add(organization.getId());
            }
        }
        List<Teacher> teacherList=teacherMapper.findTeacherList(teacher,um,orgIds);
        for (Teacher t : teacherList) {
//            PtAccount account = accountMapper.selectById(t.getId());
//            t.setAccountName(account.getAccount());
//            t.setEnable(account.getEnable());
           EntityWrapper<PtUserRole> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq("account_id",t.getId());
            entityWrapper.eq("enable",1);
            List<PtUserRole> userRoles = userRoleMapper.selectList(entityWrapper);
            t.setUserRoleList(userRoles);
            if (userRoles.size()>0){
               PtUserRole userRole0=userRoles.get(0);
                String job="";
                if (userRole0.getPhaseId()!=null) {
                    Meta meta = MetaUtils.getMeta(userRole0.getPhaseId());
                    if (meta != null) {
                        job += meta.getName();
                    }
                }
                if (userRole0.getGradeId()!=null) {
                    Meta meta = MetaUtils.getMeta(userRole0.getGradeId());
                    if (meta != null) {
                        job += meta.getName();
                    }
                }
                if (userRole0.getSubjectId()!=null) {
                    Meta meta = MetaUtils.getMeta(userRole0.getSubjectId());
                    if (meta != null) {
                        job += meta.getName();
                    }
                }
                PtRole ptRole = ptRoleMapper.selectById(userRole0.getRoleId());
                if (ptRole!=null){
                    job+=ptRole.getRoleName();
                }

                if (userRoles.size()==1){
                    t.setJob(job);
                }else {
                    t.setJob(job.concat("..."));
                }
            }else {
                t.setJob("无");
            }
        }
        return teacherList;
    }

    @Override
    public Teacher saveTeac(Integer userType, Teacher teacher) {
        PtAccount currentUser = ShiroKit.getSessionAttr(SessionKey.CURRENT_USER);
        // 初始化账号数据 机构必填
        String orgId = teacher.getOrgId();
        PtAccount acc = new PtAccount();
        acc.setOrgId(orgId);
        acc.setUserType(userType);
        String accountName = accountGenerator.validate(acc);// 自动生成用户名
        String salt ="";
        String password = EncryptPassword.encryptPassword(Const.DEFAULT_PWD);
        acc.setAccount(accountName);
        acc.setId(teacher.getId());
        acc.setEnable(true);
        acc.setPassword(password);
        acc.setSalt(salt);
        acc.setDeleted(false);
        if (ConfigUtils.readBoolConfig(MetaKeys.PHONE_LOGIN_SWITCH_KEY, true) && teacher.getCellphone() != null
                && teacher.getCellphone().matches(PtAccount.MOBILE_PHONE_NUMBER_PATTERN)) { // 验证手机
            PtAccount model = new PtAccount();// 禁用不可恢复
            model.setDeleted(false);
            model.setEnable(true);
            model.setCellphone(teacher.getCellphone());
            model = accountMapper.selectOne(model);
            if (model == null) {
                acc.setCellphone(teacher.getCellphone());
                teacher.setFlago("1");
            } else {
                teacher.setFlago("0");
            }
        }
       accountMapper.insert(acc);
        // 初始化学生数据
        teacher.setId(acc.getId());
        teacher.setCrtId(currentUser.getId());
        teacher.setCrtDttm(new Date());
        teacher.setLastupId(currentUser.getId());
        teacher.setLastupDttm(new Date());
        PtOrg org = orgService.selectById(orgId);
        teacher.setOrgName(org.getName());
        teacher.setEnable(true);
        if (StringUtils.isNotBlank(teacher.getPhoto())) {
            resourcesService.updateTmptResources(teacher.getPhoto());
        }
        teacherMapper.insert(teacher);
        //LoggerUtils.insertLogger(LoggerModule.YHGL, "用户管理——添加学校用户，用户ID：{}", teacher.getId());
        return teacher;
    }

    @Override
    public List<ExportInfoVo> exportTeacherList(UserSearchModel um) {
        String orgId="";
        List<PtOrg> orglist = new ArrayList<PtOrg>();
        List<String> orgIds = new ArrayList<String>();
        if (StringUtils.isNotEmpty(um.getOrgId())) {
            orgId=um.getOrgId();
        } else {
            if (um.getAreaId() != null) {
                orglist = orgService.getOrgByAreaId(um.getAreaId(), PtOrg.TP_SCHOOL);
            }
            for (PtOrg organization : orglist) {
                orgIds.add(organization.getId());
            }
            if (!CollectionUtils.isEmpty(orglist)) {
            } else {
                if (um.getAreaId() != null) {
                    orgId="-1";
                }
            }
        }
        return teacherMapper.findAllTeachs(orgIds,orglist,orgId);
    }

}
